package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据日期范围统计营业额数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dataList = new ArrayList();
        dataList.add(begin);

        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dataList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>(dataList.size());
        for (LocalDate date : dataList) {
            LocalDateTime minTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime maxTime = LocalDateTime.of(date, LocalTime.MAX);

            Map<String, Object> map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("begin", minTime);
            map.put("end", maxTime);

            Double turnover = ordersMapper.sumByMap(map);

            turnover = turnover == null ? 0.0 : turnover;

            turnoverList.add(turnover);
        }

        TurnoverReportVO reportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dataList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();

        return reportVO;
    }

    /**
     * 根据时间范围统计用户的新增数据和总数量
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> newUserList = new ArrayList<>(dateList.size());
        List<Integer> totalUserList = new ArrayList<>(dateList.size());

        for (LocalDate date : dateList) {
            LocalDateTime minTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime maxTime = LocalDateTime.of(date, LocalTime.MAX);

            //统计当前的新增用户的数据
            Integer newUserCount  = getUserByMap(minTime, maxTime);
            //统计当前的总用户的数据
            Integer totalUserCount = getUserByMap(null, maxTime);

            newUserCount = newUserCount == null? 0:newUserCount;
            totalUserCount = totalUserCount == null? 0:totalUserCount;

            newUserList.add(newUserCount);
            totalUserList.add(totalUserCount);
        }

        UserReportVO reportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();

        return reportVO;
    }

    /**
     * 根据时间范围统计订单数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dataList = new ArrayList<>();
        dataList.add(begin);

        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dataList.add(begin);
        }
        //每天的订单总数
        List<Integer> orderCountList = new ArrayList<>(dataList.size());
        //每天的有效订单数
        List<Integer> validOrderCountList = new ArrayList<>(dataList.size());

        for (LocalDate date : dataList) {
            LocalDateTime minTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime maxTime = LocalDateTime.of(date, LocalTime.MAX);

            Integer orderCount = getOrderCount(minTime, maxTime, null); //当天的订单总数
            Integer validOrderCount = getOrderCount(minTime, maxTime, Orders.COMPLETED); //当天的有效订单总数

            orderCount = orderCount == null ? 0 : orderCount;
            validOrderCount = validOrderCount == null ? 0 : validOrderCount;

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }

        /*Integer totalOrderCount = 0;

        for (Integer count : orderCountList) {
            totalOrderCount += count;
        }*/

        //求一个集合中的所有的元素的总和
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        /*Double orderCompletionRate = 0.0;
        if(null != totalOrderCount && totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }*/

        BigDecimal orderCompletionRate = new BigDecimal(0);
        if(null != totalOrderCount && totalOrderCount != 0){
            orderCompletionRate = new BigDecimal(validOrderCount).divide(new BigDecimal(totalOrderCount));
        }

        OrderReportVO reportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dataList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate.doubleValue())
                .build();

        String str;

        return reportVO;
    }

    /**
     * 根据时间统计销量排名前十的商品的名称和数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime minTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime maxTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesVO> list = ordersMapper.getSalesTop10(minTime, maxTime);

        /*List<String> nameList = new ArrayList<>(list.size());
        for (GoodsSalesVO vo : list) {
            nameList.add(vo.getName());
        }*/

        List<String> nameList = list.stream().map(vo -> {return vo.getName();}).collect(Collectors.toList());
        List<Integer> numberList = list.stream().map(GoodsSalesVO::getNumber).collect(Collectors.toList());

        SalesTop10ReportVO reportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();


        return reportVO;
    }

    private Integer getOrderCount(LocalDateTime minTime, LocalDateTime maxTime, Integer status) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", status);
        map.put("begin", minTime);
        map.put("end", maxTime);

        Integer count = ordersMapper.countByMap(map);

        return count;
    }

    private Integer getUserByMap(LocalDateTime minTime, LocalDateTime maxTime) {
        Map<String, Object> map = new HashMap<>();
        map.put("begin", minTime);
        map.put("end", maxTime);

        return userMapper.getUserByMap(map);
    }
}
